#ifndef __PAINTAREA__
#define __PAINTAREA__

#include <stdio.h>
#include <stdlib.h>
#include "RGBColor.h"
#include <string>
#include "ViewPlane.h"
#include <fstream>
#include <iostream>
#include <algorithm>

namespace Engine
{

#define min(A,B) (A < B? A : B)

	struct color
	{
		float r;
		float g;
		float b;

		color()
		{
			r = 0;
			g = 0;
			b = 0;
		}

		color(const float _c)
		{
			r = _c;
			g = _c;
			b = _c;
		}
	};

	class PaintArea
	{
	public:
		//ostream fp;
		ViewPlane vp;
		color *colors;
		string path;

		PaintArea(string _path, const ViewPlane& _vp)
		{
			vp = _vp;
			path = _path;
			colors = new color[vp.hres * vp.vres];
		}

		void WriteToFile()
		{
			try
			{

				int total = vp.vres * vp.hres;
				const char * charPath = path.c_str();


				ofstream fp(charPath, ios::out | ios::binary);
				fp << "P6\n" << vp.hres << " " << vp.vres << "\n255\n";
				for (int index = 0; index < total; index++)
				{
					color currentColor = colors[index];

					//writing each pixel ot file 
					fp << (unsigned char)(min(float(1), currentColor.r) * 255) <<
						(unsigned char)(min(float(1), currentColor.g) * 255) <<
						(unsigned char)(min(float(1), currentColor.b) * 255);
				}
			}
			catch (exception e)
			{
				std::cerr << e.what() << endl;
			}
		}

		bool SetPixel(const RGBColor& col, int x, int y)
		{
			try
			{
				int location = x + y*vp.hres;

				color color;
				color.r = (float)col.r;
				color.g = (float)col.g;
				color.b = (float)col.b;
				colors[location] = color;
				return true;
			}
			catch (exception e)
			{
				return false;
			}
		}

		~PaintArea()
		{
			delete[] colors;
		}
	};
}

#endif // !__PAINTAREA__
